package com.network.okhttp;

import okhttp3.*;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-04-13 16:47:05
 */
public class OkHttpUtil {

    private static final OkHttpClient client;

    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");


    static {

        client = new OkHttpClient.Builder()
                .connectTimeout(60000L, TimeUnit.MILLISECONDS)
                .readTimeout(60000L, TimeUnit.MILLISECONDS)
                .build();
    }

    /**
     * 同步发送 get 请求
     *
     * @param url 目标地址
     * @return 响应数据
     * @throws Exception 错误时抛出异常
     */
    public static String get(String url) throws Exception {
        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = client.newCall(request).execute()) {
            return Objects.requireNonNull(response.body()).string();
        }
    }

    /**
     * 异步发送 get 请求
     *
     * @param url 目标地址
     */
    public static void getAsync(String url, AtomicReference<String> result) {

        Request request = new Request.Builder()
                .url(url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String res = Objects.requireNonNull(response.body()).string();
                result.set(res);
            }
        });
    }

    /**
     * 同步发送 get 请求
     *
     * @param url    目标地址
     * @param params 参数
     * @return 响应数据
     * @throws Exception 错误时抛出异常
     */
    public static String get(String url, Map<String, String> params) throws Exception {
        HttpUrl.Builder queryUrlBuilder = HttpUrl.get(url).newBuilder();
        params.forEach(queryUrlBuilder::addQueryParameter);

        Request request = new Request.Builder()
                .url(queryUrlBuilder.build())
                .build();

        try (Response response = client.newCall(request).execute()) {
            return Objects.requireNonNull(response.body()).string();
        }

    }

    public static String post(String url, String json) throws Exception {
        RequestBody body = RequestBody.create(json, JSON);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return Objects.requireNonNull(response.body()).string();
        }
    }

    /**
     * Post请求 带Authorization认证
     */
    public static String postWithAuth(String url, String json, String user, String password) {

        final String credential = Credentials.basic(user, password);
        String result = "";
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .header("Authorization", credential)
                .post(body)
                .build();
        Call call = client.newCall(request);
        try {
            Response response = call.execute();
            //判断是否成功
            if (response.isSuccessful()) {
                result = response.body().string();
            } else {
                return "请求失败";
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭okhttp链接
                client.connectionPool().evictAll();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;

    }
}
